<?php

namespace App\Http\Controllers\Serve;

use App\Http\Controllers\Controller;
use Exception;
use Faker\Provider\Base;
use Illuminate\Http\Request;

class LoginServe extends BaseServe
{
    private $userServe;
    /**
     * @var array
     */
    private $normal_rules;
    /**
     * @var array
     */
    private $normal_message;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->userServe = new UserServe($request);
        $this->normal_rules = [
            'user_name' => $this->userServe->normal_rules['user_name'],
            'user_password' => $this->userServe->normal_rules['user_password'],
        ];
        $this->normal_message = [
            'user_name' => $this->userServe->normal_message['user_name'],
            'user_password' => $this->userServe->normal_message['user_password']
        ];
    }

    public function normal($data)
    {
        $this->validate($data, $this->normal_rules, $this->normal_message);
        $model = $this->userServe->isExit('user_name', $data['user_name']);
        if (!password_verify($data['user_password'], $model->user_password)) {
            throw new Exception(trans('user.USER_NAME_OR_PASSWORD_NOT_RIGHT', [], $this->locale), UserServe::USER_NAME_OR_PASSWORD_NOT_RIGHT);

        }
        $this->loginSuccess($model);
        return true;
    }

    public function loginSuccess($user)
    {
        session([
            'is_login' => 1,
            'user_id' => $user->id
        ]);
    }

    public function isLogin(): bool
    {
        if (session('is_login', 0) == 1) {
            return true;
        }
        return false;
    }
}
